<template>
  <div class="member-management">
    <ReCommonTable
      ref="tableRef"
      title="会员管理"
      :loading="loading"
      :data="tableData"
      :columns="columns"
      :search-fields="searchFields"
      :pagination="pagination"
      @search="handleSearch"
      @refresh="handleRefresh"
      @size-change="handleSizeChange"
      @current-change="handleCurrentPageChange"
      @selection-change="handleSelectionChange"
    >
      <!-- 添加按钮 -->
      <template #toolbar-add>
        <el-button
          type="primary"
          size="small"
          :icon="CirclePlus"
          @click="handleAdd"
          >添加会员
        </el-button>
      </template>
      <!-- 操作列 -->
      <template #astatus="{ row }">
        <el-switch
          v-model="row.m_status"
          active-value="1"
          inactive-value="-1"
          inline-prompt
          active-text="正常"
          inactive-text="删除"
          size="small"
          :loading="row._switchLoading"
          @click="handleSwitchChange(row)"
        />
      </template>
      <template #action="{ row }">
        <el-button size="small" @click="handleView(row)"> 查看</el-button>
        <el-button size="small" @click="handleEdit(row)"> 编辑</el-button>
        <el-button
          size="small"
          type="warning"
          @click="handleViewGoldLogFromTable(row)"
        >
          金币
        </el-button>
      </template>
    </ReCommonTable>

    <!-- 会员详情抽屉 -->
    <el-drawer
      v-model="detailVisible"
      title="会员详情"
      size="500px"
      direction="rtl"
    >
      <div v-if="currentMember" class="member-detail">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="会员ID">
            {{ currentMember.m_id }}
          </el-descriptions-item>
          <el-descriptions-item label="会员类型">
            {{ currentMember.m_type }}
          </el-descriptions-item>
          <el-descriptions-item label="姓名">
            {{ currentMember.m_name || "未填写" }}
          </el-descriptions-item>
          <el-descriptions-item label="手机号">
            {{ currentMember.mobile_val }}
          </el-descriptions-item>
          <el-descriptions-item label="性别">
            {{ currentMember.sex }}
          </el-descriptions-item>
          <el-descriptions-item label="金币">
            {{ currentMember.m_gold }}
          </el-descriptions-item>
          <el-descriptions-item label="最后登录日期">
            {{ currentMember.lastdate }}
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">
            {{ formatTimestamp(currentMember.m_ctime) }}
          </el-descriptions-item>
          <el-descriptions-item label="最后登录时间">
            {{ formatTimestamp(currentMember.m_lasttime) }}
          </el-descriptions-item>
          <el-descriptions-item label="备注">
            {{ currentMember.m_notes || "无" }}
          </el-descriptions-item>
        </el-descriptions>
      </div>
    </el-drawer>

    <!-- 编辑会员弹窗 -->
    <el-dialog
      v-model="editVisible"
      title="会员操作"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="editFormRef"
        :model="editForm"
        :rules="editRules"
        label-width="80px"
      >
        <el-form-item label="姓名" prop="name">
          <el-input v-model="editForm.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input
            v-model="editForm.mobile_val"
            placeholder="请输入手机号"
            @input="handleMobileInput"
          />
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-select v-model="editForm.sex" placeholder="请选择性别" clearable>
            <el-option label="未知" value="0" />
            <el-option label="男" value="1" />
            <el-option label="女" value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="note">
          <el-input
            v-model="editForm.note"
            placeholder="请输入备注"
            type="textarea"
            :rows="3"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="editVisible = false">取消</el-button>
        <el-button
          v-if="isAdding === false"
          type="primary"
          :loading="editLoading"
          @click="handleSaveEdit"
        >
          保存
        </el-button>
        <el-button
          v-if="isAdding === true"
          type="primary"
          :loading="editLoading"
          @click="handleSaveAdd"
        >
          添加
        </el-button>
      </template>
    </el-dialog>

    <!-- 金币操作弹窗 -->
    <el-dialog
      v-model="goldVisible"
      title="金币操作"
      width="400px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="goldFormRef"
        :model="goldForm"
        :rules="goldRules"
        label-width="100px"
      >
        <el-form-item label="姓名">
          <el-input v-model="goldForm.name" readonly />
        </el-form-item>
        <el-form-item label="当前金币">
          <el-input v-model="goldForm.currentGold" readonly />
        </el-form-item>
        <el-form-item label="金币增减" prop="gold">
          <el-input
            v-model="goldForm.gold"
            placeholder="请输入金币增减值（正数为增加，负数为减少）"
            type="number"
          />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="goldForm.remark"
            placeholder="请输入备注"
            type="textarea"
            :rows="3"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="goldVisible = false">取消</el-button>
        <el-button
          type="primary"
          :loading="goldLoading"
          @click="handleSaveGoldAction"
        >
          确定
        </el-button>
      </template>
    </el-dialog>

    <!-- 金币日志弹窗 -->
    <el-dialog
      v-model="goldLogVisible"
      title="金币日志"
      width="800px"
      :close-on-click-modal="false"
    >
      <!-- 会员信息和操作区域 -->
      <div class="gold-log-header">
        <div class="member-info">
          <span class="member-name">{{
            currentGoldLogMember?.m_name || "未知"
          }}</span>
          <span class="current-gold"
            >当前金币：{{ currentGoldLogMember?.m_gold || "0" }}</span
          >
        </div>
        <el-button type="primary" @click="handleGoldActionFromLog">
          操作金币
        </el-button>
      </div>

      <!-- 搜索区域 -->
      <div class="gold-log-search">
        <el-form :model="goldLogSearchForm" inline>
          <el-form-item label="备注">
            <el-input
              v-model="goldLogSearchForm.remark"
              placeholder="请输入备注关键字"
              clearable
              style="width: 200px"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleGoldLogSearch">
              搜索
            </el-button>
            <el-button @click="handleGoldLogReset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 金币日志表格 -->
      <el-table
        v-loading="goldLogLoading"
        :data="goldLogData"
        border
        style="width: 100%"
        max-height="400px"
      >
        <el-table-column prop="g_id" label="日志ID" width="80" />
        <el-table-column prop="aname" label="操作员" width="100" />
        <el-table-column prop="g_val" label="金币变化" width="100">
          <template #default="{ row }">
            <span
              :class="{
                'text-green': parseInt(row.g_val) > 0,
                'text-red': parseInt(row.g_val) < 0
              }"
            >
              {{ parseInt(row.g_val) > 0 ? "+" : "" }}{{ row.g_val }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="type" label="操作类型" width="120" />
        <el-table-column prop="g_remark" label="备注" show-overflow-tooltip />
        <el-table-column prop="cdate" label="操作时间" width="150" />
      </el-table>

      <!-- 分页 -->
      <div class="gold-log-pagination">
        <el-pagination
          v-model:current-page="goldLogPagination.current"
          v-model:page-size="goldLogPagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="goldLogPagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleGoldLogSizeChange"
          @current-change="handleGoldLogCurrentChange"
        />
      </div>

      <template #footer>
        <el-button @click="goldLogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from "vue";
import { ElMessage } from "element-plus";
import { CirclePlus, Plus } from "@element-plus/icons-vue";
import { ReCommonTable } from "@/components/ReCommonTable";
import type {
  SearchField,
  TableColumn
} from "@/components/ReCommonTable/src/index.vue";
import {
  getMemberList,
  editMember,
  addMember,
  deleteMember,
  goldAction,
  getGoldLog,
  type AddMemberParams,
  type Member,
  type MemberSearchParams,
  type EditMemberParams,
  type GoldActionParams,
  type GoldLogParams,
  type GoldLogItem
} from "@/api/member";
import { number } from "echarts";

defineOptions({
  name: "MemberManagement"
});

// 响应式数据
const loading = ref(false);
const detailVisible = ref(false);
const editVisible = ref(false);
const editLoading = ref(false);
const goldVisible = ref(false);
const goldLoading = ref(false);
const goldLogVisible = ref(false);
const goldLogLoading = ref(false);
const tableRef = ref();
const editFormRef = ref();
const goldFormRef = ref();
const selectedRows = ref([]);
const currentMember = ref<Member | null>(null);
const currentGoldLogMember = ref<Member | null>(null);

// 搜索表单
const searchForm = ref<MemberSearchParams>({});
const isAdding = ref(false);
// 编辑表单
const editForm = ref<EditMemberParams>({
  id: "",
  name: "",
  sex: "",
  mobile: "",
  note: "",
  mobile_val: ""
});

// 编辑表单验证规则
const editRules = {
  name: [{ required: true, message: "请输入姓名", trigger: "blur" }],
  mobile: [
    { required: true, message: "请输入手机号", trigger: "blur" },
    { pattern: /^1[3-9]\d{9}$/, message: "请输入正确的手机号", trigger: "blur" }
  ]
};

// 金币操作表单
const goldForm = ref({
  mid: "",
  name: "",
  currentGold: "",
  gold: "",
  remark: ""
});

// 金币操作表单验证规则
const goldRules = {
  gold: [
    { required: true, message: "请输入金币增减值", trigger: "blur" },
    { pattern: /^-?\d+$/, message: "请输入有效的数字", trigger: "blur" }
  ],
  remark: [{ required: true, message: "请输入备注", trigger: "blur" }]
};

// 金币日志相关数据
const goldLogData = ref<GoldLogItem[]>([]);
const goldLogSearchForm = ref<GoldLogParams>({});
const goldLogPagination = reactive({
  current: 1,
  size: 10,
  total: 0
});

// 表格数据
const tableData = ref([]);

// 分页配置
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0,
  pageSizes: [10, 20, 50, 100],
  layout: "total, sizes, prev, pager, next, jumper",
  background: true,
  disabled: false,
  paginationSize: "default"
});

// 搜索字段配置（根据API文档）
const searchFields: SearchField[] = [
  {
    prop: "keys",
    label: "关键字",
    type: "input",
    placeholder: "请输入姓名、手机号或手机号后4位"
  }
];

// 表格列配置（根据API文档字段）
const columns: TableColumn[] = [
  {
    prop: "m_id",
    label: "会员ID",
    width: 70,
    fixed: "left"
  },
  {
    prop: "m_name",
    label: "姓名",
    showOverflowTooltip: true
  },
  {
    prop: "m_openid",
    label: "微信OpenID"
  },
  {
    prop: "mobile_val",
    label: "手机号",
    width: 140
  },
  {
    prop: "sex",
    label: "性别",
    width: 80
  },
  {
    prop: "m_gold",
    label: "金币",
    width: 100
  },
  {
    prop: "m_status",
    label: "状态",
    width: 100,
    slot: "astatus"
  },
  {
    prop: "m_notes",
    label: "备注",
    width: 150,
    showOverflowTooltip: true
  },
  {
    prop: "m_ctime",
    label: "创建时间",
    formatter: row => formatTimestamp(row.m_ctime)
  },
  {
    prop: "lastdate",
    label: "最后登录日期"
  },
  {
    label: "操作",
    width: 200,
    fixed: "right",
    slot: "action"
  }
];

// 格式化时间戳
const formatTimestamp = (timestamp: string) => {
  if (!timestamp || timestamp === "0") return "";
  const date = new Date(parseInt(timestamp) * 1000);
  return date.toLocaleString("zh-CN", {
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
    hour: "2-digit",
    minute: "2-digit",
    second: "2-digit"
  });
};

// 事件处理
const handleSearch = (searchParams: any) => {
  console.log("搜索参数:", searchParams);
  searchForm.value = searchParams;
  pagination.current = 1;
  loadData();
};

const handleRefresh = () => {
  loadData();
};

const handleSizeChange = (size: number) => {
  pagination.size = size;
  pagination.current = 1;
  loadData();
};

const handleCurrentPageChange = (current: number) => {
  pagination.current = current;
  loadData();
};

const handleSelectionChange = (selection: any[]) => {
  selectedRows.value = selection;
};

const handleView = (row: any) => {
  currentMember.value = row;
  detailVisible.value = true;
};

const handleEdit = (row: any) => {
  editForm.value = {
    id: row.m_id,
    name: row.m_name || "",
    sex: row.m_sex || "",
    mobile: row.m_mobile || "",
    note: row.m_notes || "",
    mobile_val: row.mobile_val || ""
  };
  isAdding.value = false; // 标记为编辑操作
  editFormRef.value?.resetFields(); // 重置表单验证状态
  editVisible.value = true;
};

const handleGoldAction = (row: any) => {
  goldForm.value = {
    mid: row.m_id,
    name: row.m_name || "",
    currentGold: row.m_gold || "0",
    gold: "",
    remark: ""
  };
  goldFormRef.value?.resetFields(); // 重置表单验证状态
  goldVisible.value = true;
};

const handleViewGoldLog = () => {
  if (!currentMember.value) return;

  // 设置当前金币日志会员
  currentGoldLogMember.value = currentMember.value;

  // 重置搜索条件和分页
  goldLogSearchForm.value = {
    mid: currentMember.value.m_id
  };
  goldLogPagination.current = 1;
  goldLogPagination.size = 10;
  goldLogPagination.total = 0;

  goldLogVisible.value = true;
  loadGoldLogData();
};

const handleViewGoldLogFromTable = (row: any) => {
  // 设置当前金币日志会员
  currentGoldLogMember.value = row;

  // 重置搜索条件和分页
  goldLogSearchForm.value = {
    mid: row.m_id
  };
  goldLogPagination.current = 1;
  goldLogPagination.size = 10;
  goldLogPagination.total = 0;

  goldLogVisible.value = true;
  loadGoldLogData();
};

const handleGoldActionFromLog = () => {
  if (!currentGoldLogMember.value) return;

  goldForm.value = {
    mid: currentGoldLogMember.value.m_id,
    name: currentGoldLogMember.value.m_name || "",
    currentGold: currentGoldLogMember.value.m_gold || "0",
    gold: "",
    remark: ""
  };
  goldFormRef.value?.resetFields(); // 重置表单验证状态
  goldVisible.value = true;
};

const handleMobileInput = (val: string) => {
  editForm.value.mobile = val;
  editForm.value.mobile_val = val;
};

const handleSaveEdit = async () => {
  if (!editFormRef.value) return;

  try {
    await editFormRef.value.validate();
    editLoading.value = true;

    const response = await editMember(editForm.value);

    if (response.code === 1) {
      ElMessage.success(response.msg || "编辑成功");
      editVisible.value = false;
      loadData(); // 重新加载数据
    } else {
      ElMessage.error(response.msg || "编辑失败");
    }
  } catch (error) {
    console.error("编辑会员失败:", error);
    ElMessage.error("编辑失败");
  } finally {
    editLoading.value = false;
  }
};

const handleSaveGoldAction = async () => {
  if (!goldFormRef.value) return;

  try {
    await goldFormRef.value.validate();
    goldLoading.value = true;

    const params: GoldActionParams = {
      mid: goldForm.value.mid,
      gold: goldForm.value.gold,
      remark: goldForm.value.remark
    };

    const response = await goldAction(params);

    if (response.code === 1) {
      ElMessage.success(response.msg || "金币操作成功");
      goldVisible.value = false;
      loadData(); // 重新加载数据

      // 如果金币日志弹窗是打开的，也要刷新金币日志和会员信息
      if (goldLogVisible.value && currentGoldLogMember.value) {
        // 重新获取会员信息以更新当前金币
        const updatedMember = tableData.value.find(
          member => member.m_id === currentGoldLogMember.value?.m_id
        );
        if (updatedMember) {
          currentGoldLogMember.value = updatedMember;
        }
        loadGoldLogData(); // 重新加载金币日志
      }
    } else {
      ElMessage.error(response.msg || "金币操作失败");
    }
  } catch (error) {
    console.error("金币操作失败:", error);
    ElMessage.error("金币操作失败");
  } finally {
    goldLoading.value = false;
  }
};
const handleAdd = () => {
  // 初始化表单数据
  editForm.value = {
    id: "",
    name: "",
    sex: "",
    mobile: "",
    note: ""
  };
  isAdding.value = true; // 标记为添加操作
  editFormRef.value?.resetFields(); // 重置表单验证状态
  editVisible.value = true; // 显示编辑弹窗（复用编辑弹窗）
};
const handleSaveAdd = async () => {
  if (!editFormRef.value) return;

  try {
    await editFormRef.value.validate();
    editLoading.value = true;

    const params: AddMemberParams = {
      name: editForm.value.name,
      sex: editForm.value.sex,
      mobile: editForm.value.mobile,
      note: editForm.value.note
    };

    const response = await addMember(params);

    if (response.code === 1) {
      ElMessage.success(response.msg || "添加成功");
      editVisible.value = false;
      loadData(); // 重新加载数据
    } else {
      ElMessage.error(response.msg || "添加失败");
    }
  } catch (error) {
    console.error("添加管理员失败:", error);
    ElMessage.error("添加失败");
  } finally {
    editLoading.value = false;
  }
};
// 删除操作
const handleSwitchChange = async (row: any) => {
  try {
    // 设置 loading 状态
    row._switchLoading = true;
    // 调用更新状态的 API，比如 delAdmin
    const response = await deleteMember(row.m_id);
    if (response.code == 1) {
      ElMessage.success("状态更新成功");
    } else {
      ElMessage.error("状态更新失败");
      row.t_status = row.t_status === 1 ? -1 : 1; // 回滚状态
    }
  } catch (error) {
    console.error("状态更新出错:", error);
    ElMessage.error("状态更新失败");
    row.t_status = row.t_status === 1 ? -1 : 1; // 回滚状态
  } finally {
    // 清除 loading
    row._switchLoading = false;
  }
  await loadData();
};

// 金币日志相关方法
const loadGoldLogData = async () => {
  goldLogLoading.value = true;

  try {
    const params: GoldLogParams = {
      num: goldLogPagination.size.toString(),
      page: goldLogPagination.current.toString(),
      ...goldLogSearchForm.value
    };

    const response = await getGoldLog(params);

    if (response.code === 1) {
      goldLogData.value = response.data.list;
      goldLogPagination.total = response.data.pages * goldLogPagination.size;
    } else {
      ElMessage.error(response.msg || "金币日志加载失败");
    }
  } catch (error) {
    console.error("金币日志加载错误:", error);
    ElMessage.error("金币日志加载失败");
  } finally {
    goldLogLoading.value = false;
  }
};

const handleGoldLogSearch = () => {
  goldLogPagination.current = 1;
  loadGoldLogData();
};

const handleGoldLogReset = () => {
  goldLogSearchForm.value = {
    mid: currentGoldLogMember.value?.m_id
  };
  goldLogPagination.current = 1;
  loadGoldLogData();
};

const handleGoldLogSizeChange = (size: number) => {
  goldLogPagination.size = size;
  goldLogPagination.current = 1;
  loadGoldLogData();
};

const handleGoldLogCurrentChange = (current: number) => {
  goldLogPagination.current = current;
  loadGoldLogData();
};

// 加载数据
const loadData = async () => {
  loading.value = true;

  try {
    const params: MemberSearchParams = {
      num: pagination.size.toString(),
      page: pagination.current.toString(),
      ...searchForm.value
    };

    // 尝试调用API
    try {
      const response = await getMemberList(params);

      if (response.code === 1) {
        tableData.value = response.data.list;
        pagination.total = Number(response.data.total);
        return;
      } else {
        ElMessage.error(response.msg || "数据加载失败");
      }
    } catch (apiError) {
      console.log("API调用失败");
    }
  } catch (error) {
    console.error("数据加载错误:", error);
    ElMessage.error("数据加载失败");
  } finally {
    loading.value = false;
  }
};

// 生命周期
onMounted(() => {
  loadData();
});
</script>

<style scoped>
.member-management {
  height: 100%;
  background: #f5f7fa;
}

.member-detail {
  padding: 20px;
}

:deep(.el-descriptions) {
  --el-descriptions-item-bordered-label-background: #fafafa;
}

.dark :deep(.el-descriptions) {
  --el-descriptions-item-bordered-label-background: #262727;
}

:deep(.el-drawer__header) {
  margin-bottom: 20px;
  padding-bottom: 20px;
  border-bottom: 1px solid var(--el-border-color-light);
}

:deep(.el-drawer__body) {
  padding: 0;
}

.member-actions {
  margin-top: 20px;
  text-align: center;
}

.gold-log-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 16px;
  background: #f0f9ff;
  border-radius: 4px;
  border: 1px solid #e1f5fe;
}

.member-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.member-name {
  font-size: 16px;
  font-weight: bold;
  color: #1976d2;
}

.current-gold {
  font-size: 14px;
  color: #666;
}

.gold-log-search {
  margin-bottom: 20px;
  padding: 16px;
  background: #f5f7fa;
  border-radius: 4px;
}

.gold-log-pagination {
  margin-top: 20px;
  text-align: center;
}

.text-green {
  color: #67c23a;
  font-weight: bold;
}

.text-red {
  color: #f56c6c;
  font-weight: bold;
}
</style>
